<template>
  <canvas
    :canvas-id="canvasId"
    :id="canvasId"
    class="charts"
    :style="{ width: cWidth + 'px', height: cHeight + 'px' }"
    @touchstart="touchStart"
    @touchmove="touchMove"
    @touchend="touchEnd"
  >
  </canvas>
</template>

<script>
import uCharts from "@qiun/ucharts";

export default {
  name: "qiun-ucharts",
  props: {
    type: {
      type: String,
      default: "line",
    },
    opts: {
      type: Object,
      default() {
        return {};
      },
    },
    chartData: {
      type: Object,
      default() {
        return {};
      },
    },
    canvasId: {
      type: String,
      default: "qiun-ucharts",
    },
    cWidth: {
      type: Number,
      default: 375,
    },
    cHeight: {
      type: Number,
      default: 250,
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  watch: {
    chartData: {
      handler(val) {
        this.updateChart();
      },
      deep: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.init();
    });
  },
  methods: {
    init() {
      const ctx = uni.createCanvasContext(this.canvasId, this);
      this.chart = new uCharts({
        type: this.type,
        context: ctx,
        width: this.cWidth,
        height: this.cHeight,
        categories: this.chartData.categories || [],
        series: this.chartData.series || [],
        animation: true,
        timing: "easeOut",
        duration: 1000,
        ...this.opts,
      });
    },
    updateChart() {
      if (this.chart) {
        this.chart.updateData({
          categories: this.chartData.categories || [],
          series: this.chartData.series || [],
        });
      }
    },
    touchStart(e) {
      if (this.chart && typeof this.chart.touchStart === "function") {
        this.chart.touchStart(e);
      }
    },
    touchMove(e) {
      if (this.chart && typeof this.chart.touchMove === "function") {
        this.chart.touchMove(e);
      }
    },
    touchEnd(e) {
      if (this.chart && typeof this.chart.touchEnd === "function") {
        this.chart.touchEnd(e);
      }
    },
  },
};
</script>

<style scoped>
.charts {
  display: block;
}
</style>
